package com.xx.netty.server;

import com.xx.netty.server.handler.AisServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.concurrent.CompletableFuture;

/**
 * @description:
 * @author: xx
 * @Date 2023/7/13
 * @version: 1.0
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class AisServer {

    public static Channel clientChannel;
    private final  AisServerHandler aisServerHandler;

    /**
     * 初始化 AIS 服务器
     */
    @PostConstruct
    public void init() {
        //启动服务器
        CompletableFuture.runAsync(() -> {
            NioEventLoopGroup boss = new NioEventLoopGroup();  //创建 Boos 群组
            NioEventLoopGroup worker = new NioEventLoopGroup(); //创建 worker group
            try {
                ServerBootstrap bs = new ServerBootstrap()
                        .group(boss, worker)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<NioSocketChannel>() {
                            @Override
                            protected void initChannel(NioSocketChannel ch) {
                                clientChannel = ch;
                                ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                                ch.pipeline().addLast(aisServerHandler);
                              /*  if (clientChannel == null) {
                                    clientChannel = ch;
                                    ch.pipeline().addLast(new LineBasedFrameDecoder(1024));
                                    ch.pipeline().addLast(aisServerHandler);
                                } else {
                                    ch.close();
                                    log.warn("Rejected client connection: {}", ch.remoteAddress());
                                }*/
                            }
                   /*         @Override
                            public void channelInactive(ChannelHandlerContext ctx) throws Exception {
                                // when the client is disconnected,remove it
                                clientChannel = null;
                                super.channelInactive(ctx);
                            }*/

                        /*    @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                clientChannel = null;
                                super.exceptionCaught(ctx, cause);
                            }*/
                        });
                System.out.println("server 启动中.....");
                bs.bind(14005).sync().channel().closeFuture().sync();
            } catch (InterruptedException e) {
                log.error("server error", e);
            } finally {
                //closed event loop group
                closedEventLoopGroup(boss, worker);
            }
        });
    }

    private void closedEventLoopGroup(NioEventLoopGroup boss, NioEventLoopGroup worker) {
        boss.shutdownGracefully().addListener(future -> {
            if (future.isSuccess()) {
                log.info("sever boss closed successfully.");
            } else {
                log.error("sever boss closed failed.");
            }
        });
        worker.shutdownGracefully().addListener(future -> {
            if (future.isSuccess()) {
                log.info("sever worker closed successfully.");
            } else {
                log.error("sever worker closed failed.");
            }
        });
    }


}
